<template>
  <!-- 放大镜效果：v-if="skuImageList[0]" 有数据再渲染页面 -->
  <div class="spec-preview" v-if="imgObj">
    <img :src="imgObj.imgUrl" />
    <div class="mask" ref="mask"></div>
    <div class="big" ref="big">
      <img :src="imgObj.imgUrl" ref="bigImg" />
    </div>
    <div class="event" @mousemove="handlerPosition" @mouseenter="showMask" @mouseleave="hideMask"></div>
  </div>
</template>

<script>
export default {
  name: "ZoomIndex",
  props: ["skuImageList"],
  data() {
    return {
      newIndex: 0,
      showZoom: false
    };
  },
  computed: {
    imgObj() {
      return this.skuImageList[this.newIndex] || {};
    }
  },
  methods: {
    handlerPosition(event) {
      const mask = this.$refs.mask;
    
      const bigImg = this.$refs.bigImg;
      const preview = event.currentTarget.getBoundingClientRect();

      // 鼠标在 .event 中的坐标
      const x = event.clientX - preview.left;
      const y = event.clientY - preview.top;

      // 计算遮罩层位置（居中对齐）
      let left = x - mask.offsetWidth / 2;
      let top = y - mask.offsetHeight / 2;

      // 边界限制
      const maxLeft = preview.width - mask.offsetWidth;
      const maxTop = preview.height - mask.offsetHeight;
      if (left < 0) left = 0;
      if (top < 0) top = 0;
      if (left > maxLeft) left = maxLeft;
      if (top > maxTop) top = maxTop;

      // 设置遮罩层位置
      mask.style.left = left + "px";
      mask.style.top = top + "px";

      // 设置放大图偏移 其实就是移动.big盒子的位置到mask移动的位置（用 transform）
      bigImg.style.transform = `scale(2) translate(${-left}px, ${-top}px)`;
      bigImg.style.transformOrigin = "top left";
    },
    showMask() {
      this.$refs.mask.style.display = "block";
      this.$refs.big.style.display = "block";
    },
    hideMask() {
      this.$refs.mask.style.display = "none";
      this.$refs.big.style.display = "none";
    }
  },
  mounted() {
    //接收兄弟组件Zoom.vue传过来的图片索引值
    this.$bus.$on('setCurrentindex',(index)=> {
    
this.newIndex=index
    })
  }
}

</script>

<style lang="less" scoped>
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
    z-index: 999;
    pointer-events: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 100%;
    top: 0;
    border: 1px solid #aaa;
    overflow: hidden;
    background: white;
    display: none;
    z-index: 998;

    img {
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .event {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    cursor: crosshair;
  }
}
</style>